﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Linq;
using System.Collections.Concurrent;
using System.Threading.Tasks;
using QW.Core;
namespace QW.Core.Events
{
    /// <summary>
    /// 事件总线
    /// </summary>
    public class EventBus
    {
        private static IEventBus bus = null;
        /// <summary>
        /// 注册事件总线(由构建中心调用)
        /// </summary>
        /// <param name="bus"></param>
        internal static void Register(IEventBus bus)
        {
            EventBus.bus = bus;
        }

        /// <summary>
        /// 订阅事件处理器
        /// </summary>
        /// <param name="detail"></param>
        public static void Subscribe(EventDetail detail)
        {
            if (bus == null) { throw new EventException("事件总线未注册或注册不成功"); }
            bus.Subscribe(detail);
        }

        /// <summary>
        /// 发布事件异步
        /// <para>默认实现异步暂时会报外部错误,估计是await的地方有问题</para>
        /// </summary>
        /// <typeparam name="TEvent"></typeparam>
        /// <param name="e"></param>
        [Obsolete("默认实现异步暂时会报外部错误，请使用Publish")]
        public static void PublishAsync<TEvent>(TEvent e)
            where TEvent : class, IEvent
        {
            if (bus == null) { throw new EventException("事件总线未注册或注册不成功"); }
            bus.PublishAsync(e);
        }

        /// <summary>
        /// 发布事件同步
        /// </summary>
        /// <typeparam name="TEvent"></typeparam>
        /// <param name="e"></param>
        public static void Publish<TEvent>(TEvent e)
            where TEvent : class, IEvent
        {
            if (bus == null) { throw new EventException("事件总线未注册或注册不成功"); }
            bus.Publish(e);
        }

        /// <summary>
        /// 获取注册中的事件处理程序集
        /// </summary>
        /// <param name="name">事件名称,默认空 表示取所有</param>
        /// <returns></returns>
        public static Dictionary<string, string> GetEventHandlers(string name = "")
        {
            return bus.GetEventHandlers(name);
        }
    }
}
